package com.xpalive.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.PrivilegedAction;

public class XEnumUtils {

    public static <T extends Enum> T[] getEnumConstantsShared(Class<T> enumClass) {
        try {
            final Method values = enumClass.getMethod("values");
            java.security.AccessController.doPrivileged(
                (PrivilegedAction<Void>) () -> {
                    values.setAccessible(true);
                    return null;
                });
            @SuppressWarnings("unchecked")
            T[] temporaryConstants = (T[]) values.invoke(null);
            return temporaryConstants;
        }
        // These can happen when users concoct enum-like classes
        // that don't comply with the enum spec.
        catch (InvocationTargetException | NoSuchMethodException |
            IllegalAccessException ex) {
            return null;
        }
    }
}
